import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import { fetchValidation } from '@/utils';
import {
  queryPostManagementList,
  queryGardenList,
  operChangeStatus,
} from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    fetchGarden: Effect;
    changeStatus: Effect;
  };
  reducers: {
    save: Reducer;
    saveGarden: Reducer;
    clearGarden: Reducer;
  };
}

const stateInfo = {
  dataInfo: {
    list: [],
    count: 0,
  },
  gardenList: [],
};

const Model: ModelType = {
  namespace: 'postManagementList',

  state: stateInfo,

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryPostManagementList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },

    * fetchGarden({ payload }, { call, put }) {
      const response = yield call(queryGardenList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'saveGarden',
        payload: data.body && data.body.list ? data.body.list : [],
      });
    },

    * changeStatus({ payload: { search, ...query } }, { call, put }) {
      const response = yield call(operChangeStatus, query);
      const data = fetchValidation(response);
      if (data) {
        message.success('操作成功');
        yield data && put({
          type: 'fetch',
          payload: search,
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        dataInfo: action.payload,
      };
    },

    saveGarden(state, { payload }) {
      return {
        ...state,
        gardenList: payload,
      };
    },

    clearGarden(state) {
      return {
        ...state,
        gardenList: [],
      };
    },
  },
};

export default Model;
